package org.shiro.demo.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.shiro.demo.dao.util.QueryCondition;
import org.shiro.demo.entity.NotifyMessage;
import org.shiro.demo.service.IBaseService;
import org.shiro.demo.service.INotifyMessageService;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service("notifyMessageService")
public class NotifyMessageServiceImpl extends DefultBaseService implements INotifyMessageService {
	@Resource(name = "baseService")
	private IBaseService baseService;

	// 使用了一个缓存名叫 dbCache
	@Cacheable("message")
	public List<NotifyMessage> getAllByAdmin(String admin_id) {
		QueryCondition queryCondition = new QueryCondition("admin_id", QueryCondition.EQ, admin_id);
		List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
		queryConditions.add(queryCondition);
		List<NotifyMessage> list = baseService.get(NotifyMessage.class, queryConditions);
		return list;
	}

	@Override
	@Cacheable("message")
	public int getNumByAdmin(String adminId) {
		List<QueryCondition> list = new ArrayList<QueryCondition>();
		list.add(new QueryCondition("admin_id", QueryCondition.EQ, adminId));
		list.add(new QueryCondition("hreads", QueryCondition.EQ, false));
		int num = (int) baseService.getRecordCount(NotifyMessage.class, list);
		return num;
	}

	@Override
	@CachePut(value = "message", key = "#adminId")
	// 缓存key忽略mid
	public int updateByAdmin(String adminId, NotifyMessage nm) {
		// 更新 状态
		nm.setHreads(true);
		baseService.update(nm);
		// 重新查询 未读条数，更新到缓存
		List<QueryCondition> list = new ArrayList<QueryCondition>();
		list.add(new QueryCondition("admin_id", QueryCondition.EQ, adminId));
		list.add(new QueryCondition("hreads", QueryCondition.EQ, false));
		int num = (int) baseService.getRecordCount(NotifyMessage.class, list);
		return num;
	}
	
	@Override
	@CachePut(value = "message", key = "#adminId")
	// 缓存key忽略mid
	public int save(String adminId, NotifyMessage nm) {
		// 增加条数
		baseService.save(nm);
		// 重新查询 未读条数，更新到缓存
		List<QueryCondition> list = new ArrayList<QueryCondition>();
		list.add(new QueryCondition("admin_id", QueryCondition.EQ, adminId));
		list.add(new QueryCondition("hreads", QueryCondition.EQ, false));
		int num = (int) baseService.getRecordCount(NotifyMessage.class, list);
		return num;
	}
}
